package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"sanya-trip/cache"
	"sanya-trip/models"
	"strconv"
	"time"
)

type TripController struct {
	beego.Controller
}
type Res struct {
	Code int
	Data interface{}
	Msg  string
}

func (c *TripController) Add() {
	user := c.GetString("user")
	img := c.GetString("img")
	order := c.GetString("order")
	price, _ := c.GetFloat("price")
	if user == "" || img == "" || order == "" || price == 0 {
		c.Data["json"] = Res{
			Code: 500,
			Data: nil,
			Msg:  "标题,图片,内容,价格不能为空",
		}
		c.ServeJSON()
	}
	trip := models.Trip{
		User:  user,
		Img:   img,
		Order: order,
		Price: price,
	}
	models.Db.Create(&trip)

	data := "date_1111" + strconv.Itoa(int(trip.ID))
	marshal, _ := json.Marshal(&trip)
	cache.Rdb.Set(cache.Ctx, data, marshal, time.Hour*1)

	c.Data["json"] = Res{
		Code: 200,
		Data: trip,
		Msg:  "添加成功",
	}
	c.ServeJSON()
}

func (c *TripController) List() {
	var m []models.Trip
	date := "date_2222"
	result, _ := cache.Rdb.Get(cache.Ctx, date).Result()
	if result == "" {
		err := models.Db.Model(&models.Trip{}).Find(&m).Error
		if err != nil {
			c.Data["json"] = Res{
				Code: 500,
				Data: nil,
				Msg:  "查询失败",
			}
			c.ServeJSON()
		}
		marshal, _ := json.Marshal(&m)
		cache.Rdb.Set(cache.Ctx, result, marshal, time.Hour*2)
	} else {
		err := json.Unmarshal([]byte(result), &m)
		if err != nil {
			c.Data["json"] = Res{
				Code: 500,
				Data: nil,
				Msg:  "查询失败",
			}
			c.ServeJSON()
			return
		}
	}
	c.Data["json"] = Res{
		Code: 200,
		Data: m,
		Msg:  "查询成功",
	}
	c.ServeJSON()
}

func (c *TripController) Del() {
	id, _ := c.GetInt("id")

	var m models.Trip

	models.Db.Where("id=?", id).Delete(&m)

	date := "date_3333" + strconv.Itoa(id)

	cache.Rdb.Del(cache.Ctx, date)
	c.Data["json"] = Res{
		Code: 200,
		Data: nil,
		Msg:  "删除成功",
	}
	c.ServeJSON()
}

func (c *TripController) Update() {
	id, _ := c.GetInt("id")
	user := c.GetString("user")
	img := c.GetString("img")
	order := c.GetString("order")
	price, _ := c.GetFloat("price")
	trip := models.Trip{
		User:  user,
		Img:   img,
		Order: order,
		Price: price,
	}
	models.Db.Where("id=?", id).Updates(&trip)

	data := "date_1111" + strconv.Itoa(id)

	cache.Rdb.Del(cache.Ctx, data)

	marshal, _ := json.Marshal(&trip)
	cache.Rdb.Set(cache.Ctx, data, marshal, time.Hour*1)

	c.Data["json"] = Res{
		Code: 200,
		Data: trip,
		Msg:  "修改成功",
	}
	c.ServeJSON()
}

func (c *TripController) Image() {
	file, m, err := c.GetFile("img")
	if err != nil {
		return
	}
	defer file.Close()
	dsn := "static/img/" + m.Filename
	err = c.SaveToFile("img", dsn)
	if err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Data: nil,
			Msg:  "上传失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Data: "http://127.0.0.1:8080/" + dsn,
			Msg:  "上传成功",
		}
		c.ServeJSON()
	}
}
